package com.gaogzhen.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaogzhen.domain.DepthItemVo;
import com.gaogzhen.domain.Market;
import com.gaogzhen.domain.TurnoverOrder;
import com.gaogzhen.dto.MarketDto;
import com.gaogzhen.dto.TradeMarketDto;
import com.gaogzhen.feign.MarketServiceFeign;
import com.gaogzhen.feign.OrderBooksFeignClient;
import com.gaogzhen.mappers.MarketDtoMapper;
import com.gaogzhen.service.MarketService;
import com.gaogzhen.service.TurnoverOrderService;
import com.gaogzhen.utils.R;
import com.gaogzhen.utils.SqlExecuteUtils;
import com.gaogzhen.vo.DepthsVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @date 2022-12-08 11:24
 */
@RestController
@RequestMapping("/markets")
@Api(tags = "交易市场的数据接口")
public class MarketServiceController implements MarketServiceFeign {

    @Autowired
    private MarketService marketService;

    @Autowired
    private TurnoverOrderService turnoverOrderService;

    @Autowired
    private OrderBooksFeignClient orderBooksFeignClient;


    @GetMapping
    @ApiOperation("分页查询市场列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tradeAreaId", value = "交易市场id"),
            @ApiImplicitParam(name = "status", value = "状态"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页大小")
    })
    @PreAuthorize("hasAuthority('trade_market_query')")
    public R<Page<Market>> findByPage(@ApiIgnore Page<Market> page, Long tradeAreaId, Byte status) {
        return R.ok(marketService.findByPage(page, tradeAreaId, status));
    }

    @GetMapping("/all")
    @ApiOperation("查询所有交易市场")
    @PreAuthorize("hasAuthority('trade_area_query')")
    public R<List<Market>> findAll() {
        return R.ok(marketService.list());
    }

    @PostMapping
    @ApiOperation("新增交易市场")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "market", value = "market json数据")
    })
    public R add(@RequestBody @Validated Market market) {
        SqlExecuteUtils.sqlExceptionHandler(a -> marketService.save(a), market, "新增交易市场失败");
        return R.ok();
    }

    @PatchMapping
    @ApiOperation("修改交易市场")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "market", value = "market json数据")
    })
    public R update(@RequestBody @Validated Market market) {
        SqlExecuteUtils.sqlExceptionHandler(a -> marketService.updateById(a), market, "修改交易市场失败");
        return R.ok();
    }

    @PostMapping("/status")
    @ApiOperation("修改交易区域状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "交易区域id"),
            @ApiImplicitParam(name = "status", value = "状态值")
    })
    public R updateStatus(Long id, Byte status) {
        marketService.updateStatus(id, status);
        return R.ok();
    }

    @ApiOperation(value = "查询成交记录")
    @GetMapping("/trades/{symbol}")
    public R<List<TurnoverOrder>> findSymbolTurnoverOrder(@PathVariable("symbol") String symbol) {
        List<TurnoverOrder> turnoverOrders = turnoverOrderService.findBySymbol(symbol);
        return R.ok(turnoverOrders);
    }

    @ApiOperation(value = "通过的交易对以及深度查询当前的市场的深度数据")
    @GetMapping("/depth/{symbol}/{dept}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "symbol", value = "交易对"),
            @ApiImplicitParam(name = "dept", value = "深度类型"),
    })
    public R<DepthsVo> findDeptVosSymbol(@PathVariable("symbol") String symbol, String dept) {
        // 交易市场
        Market market = marketService.getBySymbol(symbol);

        DepthsVo depthsVo = new DepthsVo();
        depthsVo.setCnyPrice(market.getOpenPrice()); // CNY的价格
        depthsVo.setPrice(market.getOpenPrice()); // GCN的价格

        depthsVo.setAsks(Arrays.asList(new DepthItemVo(BigDecimal.valueOf(7.0), BigDecimal.valueOf(100)), new DepthItemVo(BigDecimal.valueOf(6.9), BigDecimal.valueOf(300))));
        depthsVo.setBids(Arrays.asList(new DepthItemVo(BigDecimal.valueOf(7.0), BigDecimal.valueOf(100)), new DepthItemVo(BigDecimal.valueOf(6.9), BigDecimal.valueOf(300))));
        Map<String, List<DepthItemVo>> depthMap = orderBooksFeignClient.querySymbolDepth(symbol);
        if (!CollectionUtils.isEmpty(depthMap)) {
            depthsVo.setAsks(depthMap.get("asks"));
            depthsVo.setBids(depthMap.get("bids"));
        }
        return R.ok(depthsVo);

    }


    @Override
    public MarketDto findBySymbol(String symbol) {
        return MarketDtoMapper.INSTANCE.convert2Dto(marketService.getBySymbol(symbol));
    }

    /**
     * 使用报价货币 以及 出售的货币的iD
     *
     * @param buyCoinId
     * @param sellCoinId
     * @return
     */
    @Override
    public MarketDto findByCoinId(Long buyCoinId, Long sellCoinId) {
        MarketDto marketDto = marketService.findByCoinId(buyCoinId, sellCoinId);
        return marketDto;
    }

    /**
     * 查询所有的交易市场
     *
     * @return
     */
    @Override
    public List<MarketDto> tradeMarkets() {
        return marketService.queryAllMarkets();
    }

    /**
     * 查询该交易对下的盘口数据
     *
     * @param symbol
     * @param value
     * @return
     */
    @Override
    public String depthData(String symbol, int value) {
        R<DepthsVo> deptVosSymbol = findDeptVosSymbol(symbol, value + "");
        DepthsVo data = deptVosSymbol.getData();
        return JSON.toJSONString(data);
    }

    /**
     * 使用市场的ids 查询该市场的交易趋势
     *
     * @param marketIds
     * @return
     */
    @Override
    public List<TradeMarketDto> queryMarkesByIds(String marketIds) {
        return null;
    }

    /**
     * 通过交易对查询所有的交易数据
     *
     * @param symbol
     * @return
     */
    @Override
    public String trades(String symbol) {
        return null;
    }

    /**
     * 刷新24小时成交数据
     *
     * @param symbol 交易对
     * @return
     */
    @Override
    public void refresh24hour(String symbol) {

    }
}
